package cn.qiguai.sphapi.controller;

import cn.qiguai.sphapi.controller.request.GetPageOrderParam;
import cn.qiguai.sphapi.controller.response.Status;
import cn.qiguai.sphapi.controller.response.Page;
import cn.qiguai.sphapi.controller.response.Result;
import cn.qiguai.sphapi.controller.response.UserInfo;
import cn.qiguai.sphapi.domain.Addressee;
import cn.qiguai.sphapi.domain.ShoppingCartOrder;
import cn.qiguai.sphapi.domain.User;
import cn.qiguai.sphapi.exception.SystemException;
import cn.qiguai.sphapi.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Positive;
import javax.validation.constraints.Size;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/user")
@Validated
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private ObjectMapper objectMapper;

	@PostMapping("/register")
	public Result register(@RequestBody @Validated User u) {
		return userService.register(u) ? new Result(Status.REGISTER_OK) : new Result(Status.BUSINESS_ERR);
	}

	@PostMapping("/login")
	public Result login(@RequestBody @Validated User u, HttpServletResponse resp) {
		Result re = new Result();

		String token = userService.login(u);
		/* re.setCode(token != null ? Status.LOGIN_OK : Status.LOGIN_ERR);
		re.setMsg(token != null ? "登录成功！" : "手机号或密码错误！");
		re.setData(u.getPhoneNumber()); */
		re.setStatus(token != null ? Status.LOGIN_OK : Status.LOGIN_ERR);

		if (token != null) {
			String userInfo = null;
			try {
				//将用户信息转化为json
				userInfo = objectMapper.writeValueAsString(new UserInfo(u.getId(), u.getPhoneNumber(), token));

				//由于cookie中不能包含引号，需要对其编码
				userInfo = URLEncoder.encode(userInfo, "UTF-8");
			} catch (Exception e) {
				throw new SystemException("用户信息转换错误！");
			}

			//设置cookie
			Cookie cookie = new Cookie("userInfo", userInfo);
			if (u.isAutoLogin()) { //需要自动登录
				//持久化Cookie 持续一周
				cookie.setMaxAge(7 * 24 * 3600);
			}

			//设置 Cookie 的有效路径，默认为当前路径
			cookie.setPath("/");

			//发送cookie
			resp.addCookie(cookie);
		}

		return re;
	}

	@GetMapping("/existPhoneNumber")
	public Result existPhoneNumber(@NotBlank @Size(min = 11, max = 11) String phoneNumber) {
		Result re = new Result();

		boolean flag = userService.existPhoneNumber(phoneNumber);
		re.setCode(Status.SELECT_OK.getCode());
		re.setMsg(flag ? "该手机号已被注册！" : "该手机号可用！");
		re.setData(flag);

		return re;
	}

	@PostMapping("/addToShoppingCart")
	public Result addToShoppingCart(@RequestBody ShoppingCartOrder info) {
		return userService.addToShoppingCart(info) ? new Result(Status.ADD_CART_OK) : new Result(Status.ADD_CART_ERR);
	}

	@PostMapping("/getPageShoppingCartOrder")
	public Result getPageShoppingCartOrder(@RequestBody @Validated GetPageOrderParam param) {
		return new Result(Status.SELECT_OK, userService.getPageShoppingCartOrder(param));
	}

	@GetMapping("/selectOneShoppingCartOrder/{orderId}")
	public Result selectOneShoppingCartOrder(@PathVariable @Positive int orderId) {
		return userService.selectOneShoppingCartOrder(orderId) ? new Result(Status.UPDATE_OK) : new Result(Status.UPDATE_ERR);
	}

	@PostMapping("/selectAllShoppingCartOrder")
	public Result selectAllShoppingCartOrder(@Positive int userId, boolean checked) {
		return userService.selectAllShoppingCartOrder(userId, checked) ? new Result(Status.UPDATE_OK) : new Result(Status.UPDATE_ERR);
	}

	@PostMapping("/removeShoppingCartOrder")
	public Result removeShoppingCartOrder(@Size(min = 1) int[] ids) {
		List<Integer> collect = Arrays.stream(ids).boxed().collect(Collectors.toList());

		return userService.removeShoppingCartOrder(collect) ? new Result(Status.DELETE_OK) : new Result(Status.DELETE_ERR);
	}

	@GetMapping("/getAddresseeInfo/{userId}")
	public Result getAddresseeInfo(@PathVariable @Positive int userId) {
		List<Addressee> addresseeInfo = userService.getAddresseeInfo(userId);

		return addresseeInfo != null ? new Result(Status.SELECT_OK, addresseeInfo) : new Result(Status.SELECT_ERR);
	}
}
